package com.sh.shanhuo.database.web;

import android.content.Context;

import java.util.List;

public class WebInfoDBUtils {

    public static List<WebInfoEntity> getAll(Context context) {

        WebInfoDao webInfoDao = WebInfoDatabase.getDatabase(context).getWebInfoDao();
        return webInfoDao.queryAll();
    }

    public static List<WebInfoEntity> getWebInfoBySortId(Context context, String sortId) {

        WebInfoDao webInfoDao = WebInfoDatabase.getDatabase(context).getWebInfoDao();
        return webInfoDao.findBySortId(sortId);
    }

    public static WebInfoEntity getWebInfoByWebName(Context context, String webName) {
        WebInfoDao webInfoDao = WebInfoDatabase.getDatabase(context).getWebInfoDao();
        return webInfoDao.findByWebName(webName);
    }

    public static WebInfoEntity getWebInfoByWebId(Context context, String webId) {
        WebInfoDao webInfoDao = WebInfoDatabase.getDatabase(context).getWebInfoDao();
        return webInfoDao.findByWebId(webId);
    }


    public synchronized static void insertWebInfo(Context context, WebInfoEntity webInfoEntity) {

        WebInfoDao webInfoDao = WebInfoDatabase.getDatabase(context).getWebInfoDao();
        WebInfoEntity webInfoByDB = webInfoDao.findByWebId(webInfoEntity.webId);
        if (webInfoByDB != null) {
            webInfoEntity._id = webInfoByDB._id;
            webInfoEntity.deleteFlag = 0;
            webInfoEntity.permanent = webInfoByDB.permanent;
            webInfoDao.update(webInfoEntity);
        } else {
            webInfoDao.insert(webInfoEntity);
        }
    }

    public synchronized static void disableWebInfo(Context context, WebInfoEntity webInfoEntity) {

        WebInfoDao webInfoDao = WebInfoDatabase.getDatabase(context).getWebInfoDao();
        WebInfoEntity webInfoByDB = webInfoDao.findByWebId(webInfoEntity.webId);
        if (webInfoByDB != null) {
            webInfoEntity._id = webInfoByDB._id;
            webInfoDao.update(webInfoEntity);
        } else {
            webInfoDao.insert(webInfoEntity);
        }
    }

    public static void deleteAll(Context context) {
        List<WebInfoEntity> all = getAll(context);
        WebInfoDao webInfoDao = WebInfoDatabase.getDatabase(context).getWebInfoDao();
        webInfoDao.deleteAll(all);
    }

    public static void delete(Context context, WebInfoEntity webInfoEntity) {
        WebInfoDao webInfoDao = WebInfoDatabase.getDatabase(context).getWebInfoDao();
        webInfoDao.delete(webInfoEntity);
    }

    public static void insertAll(Context context, List<WebInfoEntity> webInfoEntities) {

        deleteAll(context);
        for (int i = 0; i < webInfoEntities.size(); i++) {
            insertWebInfo(context, webInfoEntities.get(i));
        }
    }

}
